package logic

import (
	"context"
	"fmt"
	"person/models/cathe"
	"person/models/mysql"

	"person/personrpc/internal/svc"
	"person/personrpc/personrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *personrpc.RegisterRequest) (*personrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	var findUser mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&findUser)
	if findUser.ID != 0 {
		return nil, fmt.Errorf("当前账号已被注册，请前去登录")
	}
	if in.Password == "" {
		return nil, fmt.Errorf("密码不能为空")
	}
	if in.SmsCode == "" {
		return nil, fmt.Errorf("短信验证码不能为空")
	}

	sms := cathe.Rdb.Get(l.ctx, "sendSms"+"register"+in.Mobile)

	if sms.Val() != in.SmsCode {
		return nil, fmt.Errorf("短信验证码错误，请重新输入")
	}

	user := mysql.User{
		Mobile:   in.Mobile,
		Password: in.Password,
	}
	mysql.DB.Debug().Create(&user)

	return &personrpc.RegisterResponse{
		Id: int64(user.ID),
	}, nil
}
